﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Media;

namespace ViewMaker.Core.Wpf
{
    public static class DataGridDoubleClickBehavior
    {

        public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(DataGridDoubleClickBehavior), new PropertyMetadata(CommandCallback));

        public static ICommand GetCommand(DataGrid obj)
        {
            return (ICommand)obj.GetValue(CommandProperty);
        }

        public static void SetCommand(DataGrid obj, ICommand value)
        {
            obj.SetValue(CommandProperty, value);
        }

        private static void CommandCallback(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            var dataGrid = obj as DataGrid;
            if (dataGrid != null)
            {
                if (args.OldValue == null && args.NewValue != null)
                {
                    dataGrid.LoadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid_LoadingRow);
                    dataGrid.UnloadingRow += new EventHandler<DataGridRowEventArgs>(dataGrid_UnloadingRow);
                }
                else if (args.OldValue != null && args.NewValue == null)
                {
                    dataGrid.LoadingRow -= new EventHandler<DataGridRowEventArgs>(dataGrid_LoadingRow);
                    dataGrid.UnloadingRow -= new EventHandler<DataGridRowEventArgs>(dataGrid_UnloadingRow);
                }
            }
        }

        static void dataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.MouseDoubleClick += new MouseButtonEventHandler(DataGridRowMouseDoubleClickHandler);
        }


        static void dataGrid_UnloadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.MouseDoubleClick -= new MouseButtonEventHandler(DataGridRowMouseDoubleClickHandler);
        }


        static void DataGridRowMouseDoubleClickHandler(object sender, MouseButtonEventArgs e)
        {
            var row = sender as DataGridRow;
            ICommand cmd = (ICommand)GetParentDataGrid(row).GetValue(CommandProperty);
            cmd.Execute(row.Item);
        }

        private static DataGrid GetParentDataGrid(DependencyObject obj)
        {
            if (obj == null) return null;
            var parent = VisualTreeHelper.GetParent(obj);
            if (parent is DataGrid) return (DataGrid)parent;
            return GetParentDataGrid(parent);
        }

    }
}
